package com.manli.timing.beetlsql;

import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.UnderlinedNameConversion;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.BeetlSqlScannerConfigurer;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Description:
 * @Author: zrblog
 * @CreateTime: 2018-10-16 22:43
 * @Version:v1.0
 */
@Configuration
public class BeatlSQLConfig {

	// 配置包扫描
	@Bean(name = "beetlSqlScannerConfigurer")
	public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
		BeetlSqlScannerConfigurer config = new BeetlSqlScannerConfigurer();
		config.setBasePackage("com.manli.timing.dao");
		config.setDaoSuffix("Dao");
		config.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
		return config;
	}

	@Bean(name = "sqlManagerFactoryBean")
	@Primary
	public SqlManagerFactoryBean getSqlManagerFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
		SqlManagerFactoryBean factoryBean = new SqlManagerFactoryBean();

		BeetlSqlDataSource sqlDataSource = new BeetlSqlDataSource();
		sqlDataSource.setMasterSource(dataSource);
		factoryBean.setCs(sqlDataSource);
		factoryBean.setDbStyle(new MySqlStyle());
		factoryBean.setInterceptors(new Interceptor[] { new DebugInterceptor() });
		factoryBean.setNc(new UnderlinedNameConversion()); // 开启驼峰
		factoryBean.setSqlLoader(new ClasspathLoader("/sql")); // sql文件路径
		return factoryBean;
	}

	

	// 开启事务
	@Bean(name = "txManager")
	public DataSourceTransactionManager getDataSourceTransactionManager(
			@Qualifier("dataSource") DataSource dataSource) {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource);
		return transactionManager;
	}
}